package com.fulihui.wgj.schedule.job;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fulihui.common.enums.MaterialTypeEnum;
import com.fulihui.common.result.rpc.BaseResult;
import com.fulihui.common.result.rpc.SimpleResult;
import com.fulihui.common.util.RpcResultCheckUtil;
import com.fulihui.wgj.facade.dto.WxPlatformDTO;
import com.fulihui.wgj.facade.request.material.WxMaterialSyncRequest;
import com.fulihui.wgj.facade.service.material.WxMaterialService;
import com.fulihui.wgj.facade.service.platform.WxPlatformService;
import com.fulihui.wgj.schedule.annotation.MutexLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author: Levon
 * @date: 2018-07-11 14:35
 */
@Component
public class SyncWeiXinMaterialJob {

    private static final Logger LOGGER = LoggerFactory.getLogger(AuthorizerTokenJob.class);

    @Reference(version = "1.0.0")
    private WxPlatformService wxPlatformService;

    @Reference(version = "1.0.0")
    private WxMaterialService wxMaterialService;


    @MutexLock(node = "${job.node.syncMaterialJob}")
    @Scheduled(cron = "${job.cron.syncMaterialJob}")
    public void excute() {

        SimpleResult<List<WxPlatformDTO>> result = wxPlatformService.queryUsefulPlatform();
        if (RpcResultCheckUtil.isSuccess(result)) {
            List<WxPlatformDTO> datas = result.getData();
            if (CollectionUtils.isEmpty(datas)) {
                return;
            }
            for (WxPlatformDTO data : datas) {
                String appId = data.getAppId();
                WxMaterialSyncRequest request = new WxMaterialSyncRequest();
                request.setAppId(appId);
                request.setType(MaterialTypeEnum.image.getCode());
                BaseResult syncImgMaterialResult = wxMaterialService.syncMaterial(request);
                if (!RpcResultCheckUtil.isSuccess(result)) {
                    LOGGER.error("sync img material fail,result={}", syncImgMaterialResult);
                }
                request.setType(MaterialTypeEnum.news.getCode());
                BaseResult syncNewsMaterialResult = wxMaterialService.syncMaterial(request);
                if (RpcResultCheckUtil.isSuccess(syncNewsMaterialResult)) {
                    LOGGER.error("sync news material fail,result={}", syncImgMaterialResult);
                }
            }
        }
    }

}
